package com.glyxybxhtxt.controller.file;

import com.glyxybxhtxt.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Young Kbt
 * @date 2021/12/23 20:55
 * @description
 */
@RestController
@Slf4j
public class UploadPicture {

    @Value("${upload.picture_src}")
    private String pictureSavePath;
    
    @RequestMapping("/uploadPicture")
    public ResponseData uploadPicture(@RequestParam(value = "dutyPicture", required = false) MultipartFile dutyPicture) {
        if (dutyPicture.isEmpty()) {
            return new ResponseData("图片不能为空！");
        }
        // 获得文件名
        String name = dutyPicture.getOriginalFilename();
        // 后缀名
        String suffixName;
        if(name != null){
            suffixName = name.substring(name.indexOf("."));
        }else {
            return new ResponseData("文件名不能为空！");
        }
        if(!suffixName.equals(".png") && !suffixName.equals(".jpg") && !suffixName.equals(".jpeg")){
            return new ResponseData("文件格式错误");
        }
        // 指定名字和后缀
        String fileName = "duty.jpg";
        File fileDest = new File(pictureSavePath + fileName);
        try {
            if(!fileDest.exists()) {
                fileDest.mkdirs();
            }
            // 将内存中的数据写入磁盘
            dutyPicture.transferTo(fileDest);
            return new ResponseData("true","上传成功！请勿重复上传图片！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseData("上传失败！"); 
    }
}
